<template>
    <div class="sms-box">
        <span class="back" @click="back"><img src="@/assets/login/icon_back@2x.png" width="17" height="17" /> 返回</span>
        <div class="title">
            <span>验证手机号</span>
        </div>
        <div class="text">
            <span>请输入发送至 <span class="phone"> {{ filterPhone }}</span> 的验证码</span>
        </div>
        <PasswordInput ref="passwordInput" @phoneLogin="phoneLogin" @sendSms="sendSms" />
    </div>
</template>

<script lang='ts' setup>
import { defineProps, defineEmits, defineExpose, ref, Ref, computed, onMounted, PropType } from 'vue';
import { loginBySms } from '@/api/login';
import PasswordInput from './PasswordInput.vue';
import { SmsInfo } from '../loginType';
import useLocalLogin from '../hooks/useLocalLogin';

const props = defineProps({
    smsInfo: {
        type: Object as PropType<SmsInfo>,
        default: () => {}
    }
});

const emits = defineEmits(['back', 'getCode']);

const passwordInput: any = ref(null);

const filterPhone: Ref<string> = computed(() => props.smsInfo.phone.replace(/(\d{3})(\d{6})(\d{2})/, '$1******$3'));

const back = () => {
    passwordInput.value.resetPwd();
    emits('back');
};

const sendSms = () => emits('getCode', props.smsInfo);

const handleGetCode = () => passwordInput.value.handleGetCode();

// 登录
const phoneLogin = async (code: string) => {
    const data = JSON.parse(JSON.stringify(Object.assign({ ...props.smsInfo }, { code })));
    data.type = '0';
    try {
        const token = await loginBySms(data);
        useLocalLogin(token);
    } catch (error) {
        passwordInput.value.setErrorState(true);
    }
};

onMounted(() => {
    handleGetCode();
});

// 对外暴露可执行方法
defineExpose({
    handleGetCode,
});
</script>

<style lang='scss' scoped>
// 短信
.sms-box {
    height: 100%;
    background-color: #fff;
    padding: 46px 40px;
    text-align: center;
    font-family: PingFang SC-Regular, PingFang SC;
    box-sizing: border-box;
    .back {
        font-size: 14px;
        font-weight: 400;
        color: #808080;
        cursor: pointer;
        display: flex;
        align-items: center;
        position: relative;
        left: -50px;
        img {
            margin-right: 10px;
        }
    }
    .title {
        font-size: 20px;
        font-weight: 600;
        color: #333;
        margin: 46px 0 16px 0;
    }
    .text {
        font-size: 14px;
        font-weight: 400;
        color: #808080;
    }
    .phone {
        color: #333;
        font-weight: bold;
    }
}
</style>
